// array helpers
var BOARD_SIZE = 32;
function toggle(elem, inst) {
    if (elem.classList.toggle('muted')) {
        song.mute(inst);
    } else {
        song.unMute(inst);
    }
}

Array.prototype.contains = function(element) {
	for (i in this) {
		if (this[i] == element)
			return true;
	}
	return false;
};

Array.prototype.removeElement = function(value) {
	var idx = this.indexOf(value);
	if (idx != -1) {
		this.splice(idx, 1);
	}
};

// main

function Song () {
    this.data = {};
    this.data.drums = new Array();
    for (var i=0; i<32; i++) {
        this.data.drums[i] = {
            volume: 100,
            bars: new Array(BOARD_SIZE),
            mute: false
        };
    }
}

Song.prototype.toggle = function (inst, interval) {
	var elementId = createLabel(inst, interval);
	if (this.data.drums[inst].bars[interval]) {
		this.data.drums[inst].bars[interval] = 0;
		deselectTrigger(elementId);
	} else {
		this.data.drums[inst].bars[interval] = 1;
		selectTrigger(elementId);
	}
}

Song.prototype.getNote = function (inst, interval) {
    var tab = this.data.drums[inst];
    if (!tab) {
        return 0;
    }
    return tab.bars[interval] ? 1 : 0;
}

Song.prototype.mute = function (inst) {
    this.data.drums[inst].mute = true;
}

Song.prototype.unMute = function (inst) {
    this.data.drums[inst].mute = false;
}

Song.prototype.isMuted = function (inst) {
    return this.data.drums[inst].mute;
}

function saveSong(id) {
    window.localStorage.setItem(id, JSON.stringify(song.data));
}

function loadSong(id) {
    reloadSong(JSON.parse(window.localStorage.getItem(id)));
}

var first = true;
function reloadSong(data) {
    song.data = data;
    for (var i=0; i<BOARD_SIZE; i++) {
        for (var j=0; j<BOARD_SIZE; j++) {
            var elementId = createLabel(i,j);            
            if (song.getNote(i, j)) {
                selectTrigger(elementId);
            } else {
                deselectTrigger(elementId);
            }
        }
        var e = document.getElementById('inst'+i);
        if (!e) {
            continue;
        }
        var cl = e.classList;
        if (song.isMuted(i)) {
            cl.add('muted');
        } else {
            cl.remove('muted');
        }
    }
}

var soundMap = {};
var timer;


function createLabel(sound, interval) {
	return 's' + sound + 'i' + interval;
};

function changeColor(elementId, color) {
	var cell = document.getElementById(elementId);
	cell.style.backgroundColor = color;
};

function deselectTrigger(elementId) {
    if (document.getElementById(elementId)) {
        document.getElementById(elementId).classList.remove('selected');
    }
}

function selectTrigger(elementId) {
    if (document.getElementById(elementId)) {
        document.getElementById(elementId).classList.add('selected');
    }
}

function light(prev, next) {
	for (var i = 0; i < document.querySelectorAll('.instrument').length; i++) {
		var elementId = createLabel(i, prev);
		document.getElementById(elementId).classList.remove("playing");

		elementId = createLabel(i, next);
		document.getElementById(elementId).classList.add("playing");
	}
};

function eventElement(event) {
    if (event.srcElement) {
        return event.srcElement;
    } else {
        return event.originalTarget;
    }
    return null;
}

function generateSequencer(numInstruments) {
    var table = document.querySelector('table');
    table.innerHTML = '';
    for (var i=0; i<numInstruments; i++) {
        var tr = document.createElement('tr');
        var th = document.createElement('th');
        var div = document.createElement('div');
        div.classList.add('instrument');
        div.row = i;
        div.id = 'inst' + i;
        div.onclick = function (event) {
            var elem = eventElement(event);
            toggle(elem, elem.row);
        }
        th.appendChild(div);
        tr.appendChild(th);
        for (var j=0; j<BOARD_SIZE; j++) {
            var td = document.createElement('td');
            td.id = createLabel(i,j);
            td.row = i;
            td.column = j;
            td.onclick = function (event) {
                var elem = eventElement(event);
                song.toggle(elem.row, elem.column);
            }
            if ((Math.floor(j/4))%2==1) {
                td.classList.add('even');
            }
            var div = document.createElement('div');
            div.classList.add('trigger');
            td.appendChild(div);
            tr.appendChild(td);
        }
        table.appendChild(tr);
    }
    reloadSong(song.data);
};

function loadToolkits() {
	select = document.getElementById("toolkitSelection");

	// remove options
	for (var i = select.options.length - 1; i >= 0; i--) {
		select.remove(i);
	}

	// add new options
	for (toolkitName in toolkit) {
		newOption = document.createElement("option");
		newOption.value = toolkitName;
		newOption.text = toolkitName;
		select.appendChild(newOption);
	}
}

function changeToolkit() {
	var select = document.getElementById("toolkitSelection");
	for (var i = select.length - 1; i >= 0; i--) {
		if (select.options[i].selected) {
			dm.loadToolkit(select.options[i].value)
		}
	}
}

var songNames = new Array();
songNames[0] = 'spring';
songNames[1] = 'summer';
songNames[2] = 'autumn';
songNames[3] = 'winter';

function loadSongs() {
	var select = document.getElementById("songList");
	
	var songs = localStorage.getItem("songList");
	if (songs == undefined || songs == null) {
		return;
	}
	
	sList = songs.split(':');
	for (var i = 0; i < sList.length; i++) {
			var song = sList[i];

			newOption = document.createElement("option");
			newOption.value = song;
			newOption.text = song;
			select.appendChild(newOption);
			break;
	}
}

function save() {
	var select = document.getElementById("songList");
	
	var songs = localStorage.getItem("songList");
	if (songs == undefined || songs == null) {
		songs = '';
	}
	
	sList = songs.split(':');
	for (var i = 0; i < songNames.length; i++) {
		var song = songNames[i];
		if (!(sList.contains(song))) {
			// save
			saveSong(song);
			
			if (songs == '') {
				songs = song;
			} else {
				songs += ':' + song;
			}
			localStorage.setItem("songList", songs);
			
			newOption = document.createElement("option");
			newOption.value = song;
			newOption.text = song;
			select.appendChild(newOption);
			break;
		}
	}

}

function load() {
	var select = document.getElementById("songList");
	for (var i = select.length - 1; i >= 0; i--) {
		if (select.options[i].selected) {
			loadSong(select.options[i].value);
			break;
		}
	}
}
